package com.star.mentor.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.mentor.dto.EvaluationItemSaveDTO;
import com.star.mentor.dto.EvaluationItemUpdateDTO;
import com.star.mentor.entity.Evaluation;
import com.star.mentor.entity.EvaluationItem;
import com.star.mentor.mapper.EvaluationItemMapper;
import com.star.mentor.service.EvaluationItemService;
import com.star.mentor.struct.EvaluationStruct;
import com.star.mentor.vo.EvaluationItemDetailVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 评估项目明细 服务实现类
 *
 * @author yangzj
 */
@Service
public class EvaluationItemServiceImpl extends ServiceImpl<EvaluationItemMapper, EvaluationItem> implements EvaluationItemService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatch(List<EvaluationItemSaveDTO> items, Long evaluationId) {
        if (CollUtil.isEmpty(items)) {
            return;
        }
        List<EvaluationItem> collect = items.stream().map(c -> EvaluationStruct.INSTANCE.to(c)
                .setEvaluationId(evaluationId)).collect(Collectors.toList());
        this.saveBatch(collect);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBatch(List<EvaluationItemUpdateDTO> items, Long evaluationId) {
        if (CollUtil.isEmpty(items)) {
            // 删除所有的
            this.deleteByEvaluationId(evaluationId);
            return;
        }
        List<Long> oldIds = items.stream().map(EvaluationItemUpdateDTO::getId).filter(Objects::nonNull).collect(Collectors.toList());
        // 删除老的不在的
        this.lambdaUpdate().eq(EvaluationItem::getEvaluationId, evaluationId).notIn(EvaluationItem::getId, oldIds).remove();
        // 新增或更新
        List<EvaluationItem> collect = items.stream().map(c -> EvaluationStruct.INSTANCE.to(c)
                .setEvaluationId(evaluationId)).collect(Collectors.toList());
        this.saveOrUpdateBatch(collect);
    }

    @Override
    public void deleteByEvaluationId(Long evaluationId) {
        this.lambdaUpdate().eq(EvaluationItem::getEvaluationId, evaluationId).remove();
    }

    @Override
    public List<EvaluationItemDetailVO> listDetail(Long evaluationId) {
        return baseMapper.listDetail(evaluationId);
    }

    @Override
    public List<EvaluationItemDetailVO> listEvaluation(Long evaluationId, Long mentorEvaluationId) {
        return evaluationId == null ? null : baseMapper.listEvaluation(evaluationId, mentorEvaluationId);
    }
}
